<template>
  <div class="w1200">
    <el-form>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="select-param">
            <div class="form-label">
              {{ $t("订单输入") }}({{ $t("IMEI等") }})({{ $t("可选") }})
            </div>
            <div class="form-value">
              <el-input type="textarea" rows="8" v-model="imeis"></el-input>
            </div>
          </div>
        </el-col>
        <el-col :span="9">
          <div class="select-param">
            <div class="form-label">{{ $t("结果") }}({{ $t("可选") }})</div>
            <div class="form-value">
              <el-input v-model="result" :placeholder="$t('输入结果')"></el-input>
            </div>
          </div>
          <div class="select-param">
            <div class="form-label">{{ $t("服务") }}({{ $t("可选") }})</div>
            <el-select class="form-value order-service-search" v-model="serviceId" clearable filterable
              :placeholder="$t('选择_搜索服务')">
              <el-option-group class="no-divider" v-for="group in serviceList" :key="group.parent"
                :label="group.parent">
                <el-option v-for="item in group.options" :key="item.serviceId" :label="item.label"
                  :value="item.serviceId" :style="{ width: selectOptionWidth }" />
              </el-option-group>
            </el-select>
          </div>
          <div class="select-param">
            <div class="form-label">{{ $t("状态") }}({{ $t("可选") }})</div>
            <div>
              <el-select clearable class="form-value" v-model="selectStatus" :placeholder="$t('选择状态')">
                <el-option v-for="item in statsOptions" :key="item.value" :label="$t(item.label)" :value="item.value" />
              </el-select>
            </div>
          </div>
        </el-col>
        <el-col :span="9">
          <div class="select-param">
            <div class="form-label">{{ $t("创建时间") }}({{ $t("可选") }})</div>
            <div class="block form-value">
              <el-date-picker class="el-date-picker" v-model="createTimeDu" type="datetimerange"
                :start-placeholder="$t('开始日期')" range-separator="|" :end-placeholder="$t('结束日期')" />
            </div>
          </div>

          <div class="select-param">
            <div class="form-label">{{ $t("更新时间") }}({{ $t("可选") }})</div>
            <div class="block form-value">
              <el-date-picker class="el-date-picker" v-model="updateTimeDu" type="datetimerange"
                :start-placeholder="$t('开始日期')" range-separator="|" :end-placeholder="$t('结束日期')" />
            </div>
          </div>

          <div class="select-param">
            <div class="form-label">{{ $t("排序") }}({{ $t("可选") }})</div>
            <div>
              <el-select clearable class="form-value" v-model="orderByKey">
                <el-option v-for="(_, key) in orderByMap" :key="key" :label="$t(key)" :value="key" />
              </el-select>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <div class="log-panel">
      <!-- <OrderSearchDialog v-if="mobile" @dialogSearch="doSearch" :page-size="pageSize" :stats-options="statsOptions"
        :service-list="serviceList" /> -->
      <div class="op-bts" style="margin-top: 10px">
        <el-button size="medium" @click="searchByPcForm">{{
          $t("筛选")
        }}</el-button>
        <el-button size="medium" @click="countByPcForm">{{
          $t("计数")
        }}</el-button>
        <el-button size="medium" @click="resetFrom">{{ $t("重置") }}</el-button>
        <el-button size="medium" v-if="false">{{ $t("全选") }}</el-button>
        <el-button size="medium" @click="exportOrders">{{
          $t("导出全部结果")
        }}</el-button>
      </div>
      <!-- <div class="btn-list">
        <div class="btn">筛选</div>
        <div class="btn">计数</div>
        <div class="btn">重置</div>
        <div class="btn">全选</div>
        <div class="btn">导出全部结果</div>
      </div> -->

      <div class="block" style="padding: 10px 0">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50, 200]" :page-size="pageSize" :total="total"
          layout="prev, pager, next, jumper, sizes" style="text-align: center">
          <span>{{ currentPage }}</span>
        </el-pagination>
      </div>
      <div>
        <div>
          <el-table @selection-change="handleSelectionChange" :data="orderList" stripe style="width: 100%">
            <el-table-column type="selection" width="55" v-if="false" />
            <el-table-column prop="service_theme" :label="$t('服务')" width="180">
              <template slot-scope="scope">
                <span>#{{ scope.row.service_id }}
                  {{ scope.row.service_theme }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" :label="$t('金额')" width="80" />
            <el-table-column prop="ap_result" :label="$t('状态')">
              <template slot-scope="scope">
                <el-tag size="medium" :type="stateType[scope.row.ap_result]">{{
                  stateMapping(scope.row.ap_result)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="imei" :label="$t('订单输入')" width="180" />
            <el-table-column prop="result" :label="$t('结果')" width="240">
              <template slot-scope="scope">
                <span v-html="trim(scope.row.result)" />
              </template>
            </el-table-column>
            <el-table-column prop="create_time" :label="$t('创建时间')" width="100" />
            <el-table-column prop="update_time" :label="$t('更新时间')" width="100" />
            <el-table-column prop="desc" :label="$t('订单备注')" width='200' />
            <el-table-column prop="manual_order_type" :label="$t('操作')" fixed="right" width="120">
              <template slot-scope="scope">
                <el-button v-if="hasFeedBack(scope.row.manualOrderType)" size="small" type="info">{{ $t("已反馈")
                  }}</el-button>
                <el-button v-else @click="openDialog(scope.row)" size="small" type="primary">{{ $t("反馈异常")
                  }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog title="验证" :visible.sync="dialog.visible" width="30%">
      <div style="display: flex;align-items: center;">
        <el-input v-model="code" autocomplete="off" placeholder="请输入验证码"></el-input>
        <div class="vercode-mask" style="width: 160px;">
          <img v-show="imgShow" :src="vercodeImgSrc" @click="refVercode()" />
          <div class="vercode-mask" v-show="isOverdue" @click="refVercode()">
            已过期 请刷新
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="orderFeedBack(dialog.current)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import apiService from "@/api/apiService";
import { errorMsg, fetchAllData, groupByParent, isMobile } from "@/utils";
// import OrderSearchDialog from "@/views/order/OrderSearchDialog.vue";
import * as XLSX from "xlsx";
import * as util from "@/utils/index";

export default {
  name: "OrderLog",
  components: {
    // OrderSearchDialog
  },
  data() {
    return {
      stateType: {
        0: "",
        1: "info",
        2: "success",
        3: "warning",
        4: "danger",
      },
      serviceList: [],
      serviceId: "",
      selectStatus: "",
      imeis: "",
      result: "",
      orderByMap: {},
      orderByKey: "",
      orderList: [],
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      createTimeDu: [],
      updateTimeDu: [],
      searchRequest: {},
      selectedRows: [],
      exportCount: 0,
      selectOptionWidth: "",
      statsOptions: [],
      dialog: {
        visible: false,
        current: {}
      },
      code: '',
      vercodeImgSrc: "", // 验证码图片
      vercodeToken: "", // 验证码验证token
      isOverdue: false,
      imgShow: false,
    };
  },
  computed: {
    mobile() {
      return isMobile();
    },
  },
  mounted() {
    const { apResult } = this.$route.query;
    if (apResult !== undefined) {
      this.selectStatus = Number(apResult);
    }
    // this.resizeSelect();
    // window.addEventListener("resize", this.resizeSelect);
    this.getService();
    this.initSearchRequest();
    this.initOrderByList();
    this.initOrderList();
    this.statsOptions = util.getStatsOptions();
  },
  beforeDestroy() {
    // window.removeEventListener("resize", this.resizeSelect);
  },
  methods: {
    orderFeedBack(row) {
      if (this.code === '') {
        this.$message.error('请输入验证码')
        return
      }
      apiService
        .get("/order-feedback?id=" + row.id + '&code=' + this.code)
        .then((res) => {
          if (res.code === 0) {
            row.manualOrderType = 1;
            this.$message.success(res.data);

          }
        }).finally(() => {
          this.closeDialog()
        })
    },
    hasFeedBack(manualOrderType) {
      return manualOrderType === 1;
    },
    trim(result) {
      if (result) {
        let tmp = result.replace(/\\/g, "");
        // console.log(tmp)
        return tmp;
      }
      return result;
    },
    stateMapping(stateCode) {
      for (const index in this.statsOptions) {
        if (this.statsOptions[index].value === stateCode) {
          return this.statsOptions[index].label;
        }
      }
      return "未知";
    },
    resizeSelect() {
      this.$nextTick(() => {
        this.selectOptionWidth =
          this.$el.querySelector(".order-service-search").offsetWidth +
          "px !important";
      });
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows;
    },
    countByPcForm() {
      let request = this.initSearchRequestByForm();
      this.$nextTick(function () {
        apiService.post("/order-count", request).then((res) => {
          let pageCount = Math.ceil(res.data / this.pageSize);
          this.$notify({
            title: "计数完成",
            message: `共${res.data}个订单符合筛选条件，${pageCount}页`,
            type: "success",
            position: "bottom-right",
          });
        });
      });
    },
    resetFrom() {
      this.imeis = "";
      this.result = "";
      this.createTimeDu = "";
      this.serviceId = "";
      this.updateTimeDu = "";
      this.selectStatus = "";
      this.orderByKey = "";
    },
    initSearchRequest() {
      this.searchRequest.imei = "";
      this.searchRequest.result = "";
      this.searchRequest.createTimeBegin = "";
      this.searchRequest.createTimeEnd = "";
      this.searchRequest.serviceId = "";
      this.searchRequest.updateTimeBegin = "";
      this.searchRequest.updateTimeEnd = "";
      this.searchRequest.apResult = "";
      this.searchRequest.orderFiled = "update_time";
      this.searchRequest.orderBy = "desc";
      this.searchRequest.page = 1;
      this.searchRequest.pageSize = this.pageSize;
    },
    initSearchRequestByForm() {
      return {
        imei: this.imeis,
        result: this.result,
        createTimeBegin: this.createTimeDu?.[0],
        createTimeEnd: this.createTimeDu?.[1],
        serviceId: this.serviceId,
        updateTimeBegin: this.updateTimeDu?.[0],
        updateTimeEnd: this.updateTimeDu?.[1],
        apResult: this.selectStatus,
        orderFiled: this.orderByMap[this.orderByKey]?.orderFiled,
        orderBy: this.orderByMap[this.orderByKey]?.orderBy,
        page: 1,
        pageSize: this.pageSize,
      };
    },
    getService() {
      this.$nextTick(function () {
        apiService.get("/all-service", {}).then((res) => {
          this.serviceList = groupByParent(res.data);
        });
      });
    },
    /* 页大小变了依旧用之前的请求, 从第一页开始查 */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.searchRequest.page = this.currentPage;
      this.searchRequest.pageSize = val;
      this.doSearch(this.searchRequest);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchRequest.page = val;
      this.doSearch_0(this.searchRequest, false);
    },
    exportOrders() {
      let request = this.initSearchRequestByForm();
      fetchAllData("/order-list", request)
        .then((result) => {
          this.exportList(result);
        })
        .catch((error) => {
          console.log(error);
          this.$message.error(this.$t("导出订单失败"));
        });
    },
    exportList(arr) {
      console.log(arr);
      let tableData = [
        [
          "订单编号",
          "服务名称",
          "状态",
          "IMEI/SN",
          "反馈结果",
          "提交时间",
          "更新时间",
          "使用积分",
          "备注",
        ],
      ]; // 表格表头
      arr.forEach((item) => {
        let rowData = [];
        //导出内容的字段
        rowData = [
          item.id,
          "#" + item.service_id + " " + item.service_theme,
          util.stateMapping(item.ap_result),
          item.imei,
          item.result
            ?.replace(/<br>/g, "\n")
            .replace(/<("[^"]*"|'[^']*'|[^'">])*>/g, " "),
          item.create_time,
          item.update_time,
          item.price,
          item.desc,
        ];
        tableData.push(rowData);
      });
      let workSheet = XLSX.utils.aoa_to_sheet(tableData);
      let bookNew = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(bookNew, workSheet, `Results`); // 工作簿名称
      let timeStr = util.formatDateTime(new Date());
      let name = `OrderHistory ${timeStr}.xlsx`;
      XLSX.writeFile(bookNew, name); // 保存的文件名
    },
    searchByPcForm() {
      let request = this.initSearchRequestByForm();
      this.doSearch(request);
    },
    doSearch(params) {
      /* 不管是从哪发生的调用, 先把请求存起来, 这样翻页的时候能拿到之前的请求去查询 */
      this.searchRequest = params;
      this.doSearch_0(params, true);
    },
    doSearch_0(params, notify) {
      this.$nextTick(function () {
        apiService.post("/order-list", params).then((res) => {
          if (res.code === 0) {
            // console.log(res)
            this.orderList = res.data.dataList;
            this.total = res.data.total;
            if (notify) {
              this.$message.success("筛选完成");
            }
          } else {
            this.$message.error(errorMsg(res));
          }
        });
      });
    },
    initOrderByList() {
      let orderFields = [
        {
          field: "create_time",
          cname: "创建时间",
        },
        {
          field: "update_time",
          cname: "更新时间",
        },
        {
          field: "price",
          cname: "订单金额",
        },
      ];
      let orderBys = [
        {
          order: "desc",
          cname: "降序",
        },
        {
          order: "asc",
          cname: "升序",
        },
      ];
      orderFields.forEach((f) => {
        orderBys.forEach((b) => {
          this.orderByMap[f.cname + b.cname] = {
            orderFiled: f.field,
            orderBy: b.order,
          };
        });
      });
    },
    initOrderList() {
      if (JSON.stringify(this.$route.query) !== "{}") {
        this.searchRequest = this.$route.query;
        this.searchRequest.page = 1;
        this.searchRequest.pageSize = this.pageSize;
      }
      console.log(`output->this.searchRequest`, this.searchRequest)
      this.doSearch_0(this.searchRequest, false);
    },
    openDialog(row) {
      this.refVercode();
      this.dialog.visible = true
      this.dialog.current = row
    },
    closeDialog() {
      this.code = ''
      this.dialog.visible = false
      this.dialog.current = {}
    },
    refVercode() {
      const that = this;
      apiService.get("/code").then((res) => {
        that.vercodeImgSrc = res.data.imageBase64Data;
        that.vercodeToken = res.data.vercodeToken;
        this.imgShow = true;
        this.isOverdue = false;
        if (this.timer) clearInterval(this.timer);
        this.timer = setInterval(() => {
          res.data.expireTime--;
          if (res.data.expireTime <= 0) {
            that.isOverdue = true;
            this.imgShow = false;
            clearInterval(this.timer);
          }
        }, 1000);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-card__body .el-form-item {
  margin-bottom: 0;
}

.log-panel {
  text-align: left;
  background: rgb(255, 255, 255);
}

.select-param {
  width: 98%;
  text-align: left;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.op-bts {
  display: flex;
  flex-wrap: wrap;
}

.op-bts .el-button {
  color: #0d9db0;
  margin-top: 0.1rem;
}

.select-param .el-button {
  color: #0d9db0;
}

.form-label {
  font-size: smaller;
  margin-top: 0.1rem;
  font-weight: bold;
}

.form-value {
  margin-top: 0.1rem;
}

.p-col {
  flex: 0 0 auto;
  padding: 0.1rem;
  width: 100%;
}

::v-deep .el-select {
  display: block;
}

@media screen and (min-width: 992px) {
  .p-col {
    flex: 0 0 auto;
    padding: 0.5rem;
    width: 30%;
  }
}
</style>
